package com.mybatisflex.core.query;

import java.util.List;

import org.dromara.hutool.core.text.StrUtil;

import com.mybatisflex.core.dialect.IDialect;

/**
 * MySql的FIND_IN_SET函数做查询条件
 * <p>
 * 示例：
 * </p>
 * <li>FIND_IN_SET(`id`, (SELECT ... FROM ... WHERE ...))</li>
 * <li>FIND_IN_SET(`id`, '1,2,3')</li>
 * 
 * @author 胡高
 */
public class FindInSetQueryCondition extends QueryCondition {

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = 2459254841335078633L;

    private static String FIND_IN_SET = "FIND_IN_SET";

    public FindInSetQueryCondition(String logic, QueryColumn column, Object value) {
        this.setColumn(column);
        this.setLogic(logic);
        this.setValue(value);
    }

    /* (non-Javadoc)
     * @see com.mybatisflex.core.query.QueryCondition#getValue()
     */
    @Override
    public Object getValue() {
        if (this.value instanceof QueryColumn) {
            return null;
        }
        if (this.value instanceof QueryWrapper) {
            return ((QueryWrapper)this.value).getAllValueArray();
        }
        if (this.value instanceof RawQueryCondition) {
            return ((RawQueryCondition)this.value).getContent();
        }
        return super.getValue();
    }

    /* (non-Javadoc)
     * @see com.mybatisflex.core.query.QueryCondition#toSql(java.util.List, com.mybatisflex.core.dialect.IDialect)
     */
    @Override
    public String toSql(List<QueryTable> queryTables, IDialect dialect) {
        StringBuilder sql = StrUtil.builder();

        // 检测是否生效
        if (this.checkEffective()) {
            if (StrUtil.isNotBlank(this.logic)) {
                sql.append(' ');
                sql.append(this.logic);
                sql.append(' ');
            }
            sql.append(FIND_IN_SET).append("(");

            /*
             * 第一个参数
             */
            sql.append(this.getColumn().toConditionSql(queryTables, dialect));

            // 参数之间的分隔
            sql.append(", ");

            /*
             * 第二个参数
             */
            if (this.value instanceof QueryColumn) {
                sql.append(((QueryColumn)this.value).toConditionSql(queryTables, dialect));
            }
            // 子查询
            else if (this.value instanceof QueryWrapper) {
                sql.append("(").append(dialect.buildSelectSql((QueryWrapper)this.value)).append(")");
            }
            // 原生sql
            else if (this.value instanceof RawQueryCondition) {
                sql.append(((RawQueryCondition)this.value).getContent());
            }
            // 正常查询，构建问号
            else {
                this.appendQuestionMark(sql);
            }

            sql.append(")");
        }

        return sql.toString();
    }

}
